package com.frozenc.controller.edit;

import com.frozenc.domain.News;
import com.frozenc.domain.User;
import com.frozenc.enums.UserType;
import com.frozenc.mapper.NewsMapper;
import com.sun.deploy.net.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.IOException;

/**
 * Created by FrozenC on 2016/9/12.
 */
@Controller
@RequestMapping("/edit")
public class editor {

    @Autowired
    private NewsMapper newsMapper;

    @ModelAttribute
    public void setUser(HttpSession session,ModelMap modelMap){
        User user = (User) session.getAttribute("currUser");
        modelMap.addAttribute("currUser",user);
    }

    @RequestMapping(value = {"/",""},method = RequestMethod.GET)
    public ModelAndView getEdit(ModelMap modelMap,HttpServletResponse response){
        User user = (User) modelMap.get("currUser");

        if(user==null || user.getUserType()==null || !user.getUserType().hasEditAuth()){
            return new ModelAndView("redirect:/");
        }

        modelMap.addAttribute("news",new News());

        return new ModelAndView("edit");
    }

    @RequestMapping(value = {"/",""},method = {RequestMethod.POST,RequestMethod.PUT})
    @ResponseBody
    public String postEdit(@RequestBody @Valid News news, ModelMap modelMap, HttpServletRequest request){
        User user = (User) modelMap.get("currUser");

        if(user!=null && user.getUserType().hasEditAuth()){
            news.setAuthor(user.getUsername());
        }
        else{
            return "未登录或无权限";
        }

        news.setCategory("科技");

        int ans = 0;
        try{
            if(request.getMethod().equalsIgnoreCase("POST")){
                ans = newsMapper.insertNews(news);
            }
            else{
                News originNews = newsMapper.selectNewsById(news.getId());
                if(originNews == null){
                    return "非法提交";
                }
                if(!user.getUserType().hasAdminAuth() && !originNews.getAuthor().equals(user.getUsername())){
                    return "没有编辑权限";
                }
                ans = newsMapper.updateNews(news);
            }
        }catch (DataAccessException e){
            System.out.println(e.getMessage());
            return "failed";
        }
        System.out.println(ans);

        return "ok";
    }
}
